package com.zxw.auth.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zxw.common.core.base.constant.SecurityConstants;
import com.zxw.common.core.base.res.BaseRes;
import com.zxw.common.web.util.JwtUtils;
import com.zxw.common.web.util.RequestUtils;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.Principal;
import java.util.Map;

@Api(tags = "认证中心")
@RestController
@RequestMapping("/oauth")
@Slf4j
public class AuthController {

    @Resource
    private KeyPair keyPair;

    @Value("${testUserCompanyId}")
    private Long testUserCompanyId;


    @Resource
    private TokenEndpoint tokenEndpoint;

    //    @ApiOperation(value = "OAuth2认证", notes = "登录入口")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "grant_type", defaultValue = "password", value = "授权模式", required = true),
//            @ApiImplicitParam(name = "client_id", defaultValue = "erp_cloud", value = "Oauth2客户端ID", required = true),
//            @ApiImplicitParam(name = "client_secret", defaultValue = "123456", value = "Oauth2客户端秘钥", required = true),
//            @ApiImplicitParam(name = "refresh_token", value = "刷新token"),
//            @ApiImplicitParam(name = "username", defaultValue = "zxw", value = "用户名"),
//            @ApiImplicitParam(name = "password", defaultValue = "pass", value = "用户密码")
//    })
    @PostMapping("/token")
    public Object postAccessToken(Principal principal,
                                  @RequestParam Map<String, String> parameters
    ) throws HttpRequestMethodNotSupportedException {

        /**
         * 获取登录认证的客户端ID
         *
         * 兼容两种方式获取Oauth2客户端信息（client_id、client_secret）
         * 方式一：client_id、client_secret放在请求路径中(注：当前版本已废弃)
         * 方式二：放在请求头（Request Headers）中的Authorization字段，且经过加密，例如 Basic Y2xpZW50OnNlY3JldA== 明文等于 client:secret
         */
        String clientId = RequestUtils.getOAuth2ClientId();
        log.info("OAuth认证授权 客户端ID:{}，请求参数：{}", clientId, JSONUtil.toJsonStr(parameters));


        OAuth2AccessToken accessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        if (accessToken.getAdditionalInformation().get("companyId").equals(testUserCompanyId)) {
            return BaseRes.oKToken(accessToken, accessToken.getTokenType(), accessToken.getValue());
        } else {
            return BaseRes.ok(accessToken);
        }

    }

}
